//	Copyright (C) 2010  Thomas Andersen (thomas.1.andersen@gmail.com)
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//	
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//	
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.	

function SendCheckSession()
{
    // Check if cookies work.
    createCookie("OpenSecretTest","1",1);
    if (readCookie("OpenSecretTest") == "1") {
        eraseCookie("OpenSecretTest");
        document.itemlistwindows = new Array();
        document.itemdetailwindows = new Array();
        document.look = 0;
        
        var sessionid = readCookie("OpenSecretSession")
        if (sessionid)
        {
            var pl = new XMLReqParameters();
            pl.add("sessionid", sessionid);
            XMLReq.invoke("service.php", "CheckSession", pl, false, SendCheckSession_callBack);
        } else {
            Unknown();
            SetupStartWindows();
        }
    } else {
        ShowErrorNoCookies();
    }
}

function LoginOpen()
{
var html = "<form class=loginform id=\"LoginForm\" name=\"LoginForm\" onsubmit=\"SendLogin(); return false;\">";
    html += "<fieldset>";
    html += "<legend>Login</legend>";
        html += "<input id=\"user\" name=\"user\" type=\"hidden\" value=\"\"/>";
        html += "<input id=\"pass\" name=\"pass\" type=\"hidden\" value=\"\"/>";
        html += "<input id=\"value\" name=\"Session\" type=\"hidden\" value=\"\"/>";
            html += "<label for=userid>Username:</label><input class=loginitem type=\"text\" id=\"userid\" name=\"userid\" size=\"20\" maxlength=45/><br/>";
            html += "<label for password>Password:</label><input class=loginitem type=password id=\"password\" name=password size=20 maxlength=20><br/>";
            html += "<input class=loginitem type=submit name=Submit value=Login disabled=true>";
    html += "</fieldset>";
    html += "</form>";
    document.getElementById("mainform").innerHTML = html;
    LoginWinFocus();
}

function SetupStartWindows()
{
    LoginOpen();
}

function SendCheckSession_callBack(doc)
{
    var parser = new XMLRequestParser(doc);
    if (parser.CheckError())
    {
        alert(parser.GetError());
    }
    var sessionid = parser.GetField("sessionid");
    var known = parser.GetField("known");
    var admin = parser.GetField("admin");
    document.admin = admin;
    document.known = known;
    if (known)
    {
        Authenticated(sessionid);
    }
    else
    {
        Unknown();
        SetupStartWindows();
    }
} 




function SendLogin()
{
    document.LoginForm.Submit.disabled = true;
    var pl = new XMLReqParameters();
    pl.add("sessionid", document.LoginForm.Session.value);
    pl.add("name", document.LoginForm.userid.value);
    pl.add("password", hex_md5(hex_md5(document.LoginForm.password.value) + document.LoginForm.Session.value));
	createCookie("OpenSecretKey",hex_md5(hex_md5("$Secret" + document.LoginForm.password.value + "$Key")),3);

    XMLReq.invoke("service.php", "Login", pl, true, SendLogin_callBack);
}

function SendLogin_callBack(doc)
{
    var parser = new XMLRequestParser(doc);
    if (parser.CheckError())
    {
        alert(parser.GetError());
    }
    var sessionid = parser.GetField("sessionid");
    var known = parser.GetField("known");
    document.known = known;
    if (known)
    {
    	Authenticated(sessionid);
    }
    else
    {
        document.LoginForm.Submit.disabled = false;
        Unknown();
        alert("Login failed. Please try again!");
    }
} 

function Authenticated(sessionid)
{
    var html = "<div class=Choices><a href='' onClick=\"SafeNew('','',''); return false;\">New item</a>";
    html = html + "<a href='' onClick=\"ShowSafe(); return false;\">Search</a>";
    html += "<a href='logout' onClick=\"Logout(); return false;\">Logout</a></div>";
    document.getElementById("mainoptions").innerHTML = html;

    ShowSafe();
}

function Logout()
{
    var sess = readCookie('OpenSecretSession');
    if (sess)
    {
        var pl = new XMLReqParameters();
        pl.add("sessionid", sess);
        XMLReq.invoke("service.php", "Logout", pl, true /*, No callback*/);
        eraseCookie("OpenSecretSession");
        document.getElementById("maininfo").innerHTML = "";
        document.getElementById("mainform").innerHTML = "";
    }
    SendCheckSession();
}

function CloseAll()
{
    document.itemlistwindows = new Array();
    document.itemdetailwindows = new Array();
}

function Unknown()
{
    var html = "<div class=Choices><a href='' onClick=\"LoginOpen(); return false;\">Login</a>";
    html += "<a href='' onClick=\"NewUserOpen(); return false;\">New user</a></div>";
    document.getElementById("mainoptions").innerHTML = html;
}

function ShowErrorNoCookies()
{
    var html = "We are very sorry, but this site requires cookies to be enabled.<br/>Please enable cookies and refresh window.";
    document.getElementById("mainoptions").innerHTML = html;
}


function ChangeLook()
{
    if (document.look == 0) {
        document.getElementById('ss').href = 'styles/alternative.css?version=1';
        document.look = 1;
    } else {
        document.getElementById('ss').href = 'styles/opensecrets.css?version=1';
        document.look = 0;
    }
}

function LoginWinFocus(parm,window)
{
    document.LoginForm.userid.focus();
    var sess = readCookie('OpenSecretSession');
    if (sess)
    {
        document.LoginForm.Session.value = sess;
        document.LoginForm.Submit.disabled = false;
    } else {    
        var pl = new XMLReqParameters();
        pl.add("empty", "empty");
        XMLReq.invoke("service.php", "Challenge", pl, true, SendChallenge_callBack);
    }
}

function SendChallenge_callBack(doc,text)
{
    var parser = new XMLRequestParser(doc);
    if (parser.CheckError())
    {
        alert(parser.GetError());
    }
    else
    {
        var sess = parser.GetField("value");
        if (sess)
        {
            createCookie("OpenSecretSession",sess,3);
            document.LoginForm.Session.value = sess;
            document.LoginForm.Submit.disabled = false;
            document.admin = 0;
            document.known = 0;
            SetupStartWindows();
        }
    }
}


function encode(txt){
    txt = txt.replace(/[&]/g,'&amp;');
    txt = txt.replace(/[<]/g,'&lt;');
    txt = txt.replace(/[>]/g,'&gt;');
    txt = txt.replace(/[\']/g,'&#39;');
    txt = txt.replace(/[\"]/g,'&quot;');
    return txt;
}
